package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.PageParam;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/category")
@RestController
public class CategoryController {
    
    @Autowired
    private CategoryService cs;
    
    /**
     * 根据分类的类型来查询分类数据
     * @param type
     * @return
     */
    @GetMapping("/list")
    public R list(Integer type){ // Integer type = null;  | Integer type = 1 |  Integer type = 2
        try {
            //1. 调用service
            List<Category> list = cs.findCategoryByType(type);
        
            return R.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("查询分类失败！");
        }
    }
    
    /**
     * 更新分类
     * @param category
     * @return
     */
    @PutMapping
    public R update(@RequestBody Category category){
        
        //1. 调用service
        int row = cs.update(category);
        
        //2. 判定
        if(row >0){
            return R.success("更新成功！");
        }else{
            return R.error("更新失败！");
        }
    
    }
    
    /**
     * 删除分类
     * @param id
     * @return
     */
    @DeleteMapping
    public R delete(Category c){
    
        System.out.println("c = " + c);
        //1. 调用service
        int row =1 ; // cs.delete(id);
        
        //2. 判定
        if(row >0 ){
            return R.success("删除分类成功！");
        }else{
            return R.error("删除分类失败！");
        }
    }
    
    /**
     * 分页查询
     * @param pageParam
     * @return
     */
    @GetMapping("/page")
    public R findPage(PageParam pageParam){
    
        try {
            //1. 调用service
            IPage<Category> page = cs.findPage(pageParam);
        
            //2. 返回
            return R.success(page);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("分页查询失败！");
        }
    
    }
    
    /**
     * 添加分类
     * @param category
     * @return
     */
    @PostMapping
    public R add(@RequestBody Category category){
    
        //1. 调用service
        int row = cs.add(category);
        
        //2. 判定
        if(row >0){
            return R.success("添加分类成功");
        }else{
            return R.error("添加分类失败");
        }
    }
}
